/// <reference path="index.d.ts" />

import Taro from "@tarojs/taro"

export const events: Taro.Events = new Taro['Events']()


interface MessageType {
    /**设置rn navigationBar的标题 */
    setTitle,
    /**给web配置AppModel信息 */
    setAppModel,
    /**changeToWorkstate */
    changeToWorkstate
}



export type Message = {
    type: keyof MessageType,
    data: any
}


/**
 * rn 发送过来的消息
 * @param msg 
 */
window.getMessageFromRn = (msg) => {
    try {
        events.trigger('getMessageFromRn', JSON.parse(msg) as Message)
    } catch (error) {
        alert('JSON-string格式化错误!')
    }
}

/**
 * 监听rn发送过来的消息
 * @param listener 
 */
export const onMessageFromRn = (listener: (msg: Message) => void) => events.on('getMessageFromRn', listener)

/**
 * 取消监听
 */
export const offMessageFromRn = () => events.off('getMessageFromRn')

/**
 * 给rn发送消息
 * @param msg 
 */
export const setMessageToRn = (msg: Message) => {
    window.ReactNativeWebView?.postMessage(JSON.stringify(msg))
}



